package model.world;

import game_engine.GameEngine;
import game_engine.display.GEWindowOGL;

import java.util.Random;

import resources.ImageHandler;

public class WorldGenerator {

	private static WorldGenerator instance;
	private Random myRandom;
	private int[][] lastIteration = new int[GameEngine.resolution.width/20][GameEngine.resolution.height/20+1];
	private Integer[][] link;
	
	
	private WorldGenerator() {
		long seed = new Random().nextLong();
		System.out.println("WORLD SEED IS  : " + seed);
		ImageHandler.getInstance().loadWorld("resources/world1.txt");
		link = ImageHandler.getInstance().getLink();
		myRandom = new Random(seed);
		for(int i = 0; i < lastIteration.length ; i++) {
			for(int j = 0 ; j < lastIteration[i].length ; j++) {
				int leftImage = -1, topImage = -1;
				if(j!=0)topImage = lastIteration[i][j-1];
				if(i!=0)leftImage = lastIteration[i-1][j];
				lastIteration[i][j] = getImage(leftImage, topImage, -1);
			}
		}
	}
	
	private int getImage(int leftImage, int topImage, int botImage) {
		if(topImage!=-1 && link[topImage][2]!=null) return link[topImage][2];
		if(leftImage!=-1 && link[leftImage][3]!=null) return link[leftImage][3];
		if(botImage!=-1 && link[botImage][0]!=null) return link[botImage][0];
		int image = -1;
		int rand = myRandom.nextInt(100);
		int add = 0;
		for(int i = 0;i<link.length;i++) {
			if(link[i][4]!=null && link[i][4]!=-1)
				if(rand>=add && rand<=(add+link[i][4])){
					return i;
				}
				else add+=link[i][4];
		}
		return image;
	}
	
	public static WorldGenerator getInstance() {
		if(instance==null) instance = new WorldGenerator();
		return instance;
	}
	
	public int[][] getNextImage() {
		int[][] images =  new int[GameEngine.resolution.width/20][GameEngine.resolution.height/20+1];
		for(int i = 0; i < images.length ; i++) {
			for(int j = 0; j < images[i].length ; j++) {
				if(j == 0) {
					int leftImage = -1, botImage=-1;
					if(i!=0)leftImage = images[i-1][0];
					if(j!=images[i].length-1)botImage = lastIteration[i][0];
					images[i][j] = getImage(leftImage, -1, botImage);
				}
				else images[i][j] = lastIteration[i][j-1];
			}
		}
		lastIteration = images;
		return lastIteration;
	}
}
